package org.budo.spring.velocity.resource.loader;

import java.io.InputStream;

import org.apache.commons.lang.StringUtils;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.apache.velocity.util.ClassUtils;
import org.apache.velocity.util.ExceptionUtils;
import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author limingwei
 */
public class BudoClasspathResourceLoader extends ClasspathResourceLoader {
    private static final Logger log = Slf4j.getLogger();

    private String resourceLoaderPath;

    @Override
    public InputStream getResourceStream(String name) throws ResourceNotFoundException {
        if (StringUtils.isEmpty(name)) {
            throw new ResourceNotFoundException("No template name provided, name=" + name);
        }

        String path = null;
        try {
            path = this.resourceNameToPath(name);

            InputStream inputStream = null;
            try {
                inputStream = ClassUtils.getResourceAsStream(this.getClass(), path);
            } catch (Exception e) {
                Throwable e2 = ExceptionUtils.createWithCause(ResourceNotFoundException.class, "#33 name=" + name + ", path=" + path, e);
                throw (ResourceNotFoundException) e2;
            }

            if (inputStream == null) {
                String msg = "#37 ClasspathResourceLoader Error: cannot find name=" + name + ", path=" + path;
                throw new ResourceNotFoundException(msg);
            }

            return inputStream;
        } catch (ResourceNotFoundException e) {
            log.info("#43 name=" + name + ", path=" + path, e);
            throw e;
        }
    }

    private String resourceNameToPath(String name) {
        String path = this.getResourceLoaderPath() + "/" + name;

        while (true) { // 替换双斜线
            if (path.contains("//")) {
                path = path.replace("//", "/");
            } else {
                break;
            }
        }

        // 去掉 classpath
        if (path.toLowerCase().startsWith("classpath:")) {
            path = path.substring(10);
        }

        return path;
    }

    public String getResourceLoaderPath() {
        return this.resourceLoaderPath;
    }

    public void setResourceLoaderPath(String resourceLoaderPath) {
        this.resourceLoaderPath = resourceLoaderPath;
    }
}